/**
 * @file CMBacktraceSelf.h
 * @brief debug 调试段错误，栈回溯等功能封装
 * @todo 此功能尚未完善，待后期添加
 */

#ifndef CMSL_CMBACKTRACESELF_H
#define CMSL_CMBACKTRACESELF_H

#include <dlfcn.h>
#include <signal.h>
#ifdef __cplusplus
extern "C"
{
#endif

#if 0
typedef struct
{
    const char *dli_fname;  /* File name of defining object.  */
    void *dli_fbase;        /* Load address of that object.  */
    const char *dli_sname;  /* Name of nearest symbol.比如函数名*/
    void *dli_saddr;        /* Exact value of nearest symbol.比如函数的起始地址*/
} Dl_info;
#endif

    typedef struct ucontext_ce123
    {
        unsigned long     uc_flags;
        struct ucontext * uc_link;
        stack_t           uc_stack;
        struct sigcontext uc_mcontext;
        sigset_t          uc_sigmask; /* mask last for extensibility */
    } ucontext_ce123_;

    typedef struct sigframe_ce123
    {
        struct sigcontext sc; //保存一组寄存器上下文
        unsigned long     extramask[1];
        unsigned long     retcode; //保存返回地址
        // struct aux_sigframe aux __attribute__((aligned(8)));
    } sigframe_ce123;

#ifdef __cplusplus
}
#endif

class CMBacktraceSelf
{
  public:
    char **print_call_stack(ucontext_t *uc, int *size);
    void   print_backtrace_normal(void **array, int size);

  protected:
    char **backtrace_symbols_self(void *const *array, int size);
    int    addr_to_name(void *addr, Dl_info *dl_info, char *name);
};

#endif // CMSL_CMBACKTRACESELF_H
